package org.darcy.controller.admin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.darcy.config.property.AppProperties;
import org.darcy.entity.SysUser;
import org.darcy.framework.annotation.BussinessLog;
import org.darcy.framework.blog.holder.RequestHolder;
import org.darcy.framework.model.ResponseVO;
import org.darcy.framework.util.ResultUtil;
import org.darcy.framework.util.SessionUtil;
import org.darcy.model.SysUserModel;
import org.darcy.model.UserPwd;
import org.darcy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import lombok.extern.slf4j.Slf4j;

/**
 * 后台用户登录
 *
 */
@Slf4j
@Controller
@RequestMapping(value = "/admin/security")
public class LoginController {

	@Autowired
	private AppProperties config;

	@Autowired
	private SysUserService userService;

	@BussinessLog("用户注册页面")
	@GetMapping("/register")
	public ModelAndView register() {
		return ResultUtil.view("/admin/register");
	}

	@BussinessLog("用户注册")
	@PostMapping("/register")
	@ResponseBody
	public SysUserModel register(SysUserModel user) {
		SysUserModel data = userService.register(user);
		return data;
	}

	@BussinessLog("进入登录页面")
	@GetMapping("/login")
	public ModelAndView login(Model model) {
		model.addAttribute("enableKaptcha", config.isEnableKaptcha());
		return ResultUtil.view("/admin/login");
	}

	@BussinessLog("[{1}]登录系统")
	@PostMapping("/signin")
	@ResponseBody
	public ResponseVO signin(String username, String password, boolean rememberMe, String kaptcha) {
		if (config.isEnableKaptcha()) {
			if (StringUtils.isEmpty(kaptcha) || !kaptcha.equals(SessionUtil.getKaptcha())) {
				return ResultUtil.error("验证码错误！");
			}
			SessionUtil.removeKaptcha();
		}
		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
			SavedRequest savedRequest = WebUtils.getSavedRequest(RequestHolder.getRequest());
			String historyUrl = null;
			if (null != savedRequest) {
				if (!savedRequest.getMethod().equals("POST")) {
					historyUrl = savedRequest.getRequestUrl();
				}
			}
			RequestHolder.setSession("user", currentUser.getPrincipal());
			return ResultUtil.success(null, historyUrl);
		} catch (Exception e) {
			log.error("登录失败，用户名[{}]：{}", username, e.getMessage());
			token.clear();
			return ResultUtil.error(e.getMessage());
		}
	}

	@BussinessLog("修改密码")
	@PostMapping("/updatePwd")
	@ResponseBody
	public ResponseVO updatePwd(@Validated UserPwd userPwd, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
		}
		boolean result = userService.updatePwd(userPwd);
		SessionUtil.removeAllSession();
		return ResultUtil.success(result ? "密码已修改成功，请重新登录" : "密码修改失败");
	}
	
	@BussinessLog("修改个人信息")
	@PostMapping("/updateProfile")
	@ResponseBody
	public ResponseVO updateProfile(@Validated SysUser user, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
		}
		userService.update(user);
		return ResultUtil.success("个人信息修改成功");
	}

	/**
	 * 使用权限管理工具进行用户的退出，跳出登录，给出提示信息
	 *
	 * @param redirectAttributes
	 * @return
	 */
	@BussinessLog("退出系统")
	@GetMapping("/logout")
	public ModelAndView logout(RedirectAttributes redirectAttributes) {
		redirectAttributes.addFlashAttribute("message", "您已安全退出");
		return ResultUtil.redirect("/admin/index");
	}
}
